/*
 * @Author: 阿芙
 * @Date: 2021-04-11 12:33:18
 * @LastEditTime: 2021-06-26 00:00:47
 * @LastEditors: Please set LastEditors
 * @Description: 
 * @FilePath: /Init-Template-express/src/com/HY/Xiao-Jun-Jun/app.js
 */



//http报错日志
var createError = require('http-errors');

//express模块
var express = require('express');

var fs = require("fs");

//path模块
var path = require('path');

//cookie模块
var cookieParser = require('cookie-parser');

//http日志
var morgan = require('morgan');

//ejs模板
const ejs = require("ejs")

//session模块
const session = require("express-session");

//API请求
const CommonApi = require("../../../../ruoling-middleware/src/com/ruoling/middleware/middlewareApi/CommonApi.js");

//日志log4js
const log4js = require("../../../../ruoling-common/src/com/ruoling/common/core/log4js.js");
const logger = log4js.getLogger();


var app = express();

//存储 http 日志
log4js.useLogger(app,logger)

app.use(session({
  secret: 'this is string key',   // 可以随便写。 一个 String 类型的字符串，作为服务器端生成 session 的签名
  name:'session_id',/*保存在本地cookie的一个名字 默认connect.sid  可以不设置*/
  resave: false,   /*强制保存 session 即使它并没有变化,。默认为 true。建议设置成 false。*/
  saveUninitialized: true,   //强制将未初始化的 session 存储。  默认值是true  建议设置成true
  cookie: {
      maxAge:1000*30*60    /*过期时间*/

  },   /*secure https这样的情况才可以访问cookie*/

  //设置过期时间比如是30分钟，只要游览页面，30分钟没有操作的话在过期

  rolling:true //在每次请求时强行设置 cookie，这将重置 cookie 过期时间（默认：false）
}));

//启动数据库
const {MYSQL} = require("../../../../ruoling-common/src/com/ruoling/common/config/mysqlconfig.js");
MYSQL("数据库启动中。。。");

//在线状态定时任务
const ScheduleOnline = require("../../../../ruoling-common/src/com/ruoling/common/core/scheduleonline.js");
const StartupConfig = require("../../../../ruoling-common/src/com/ruoling/common/config/startupconfig.js");

// view engine setup
/**
 * 模板配置
 */
app.engine(".html",ejs.__express);

 //视图文件路径
app.set('views', path.join(__dirname, "../../resources/template"));

app.set('view engine', 'html');

app.locals.web_title = StartupConfig.web_title;


app.use(express.json());

//等于true的原因是，使用了第三方 qs处理
app.use(express.urlencoded({ extended: true }));

//配合session使用
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "../../resources/public")));



/**
 * API和路由配置
 */


// 允许跨域
app.all('*', function(req, res, next) {
  
  // console.log(req.headers.origin)
  // console.log(req.environ)
  //res.header("Access-Control-Allow-Origin", req.headers.origin);
  res.header("Access-Control-Allow-Origin", '*');
  res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.header("Access-Control-Allow-Credentials","true");
  res.header("X-Powered-By",' 3.2.1')
  if(req.method === "OPTIONS") res.send(200);/*让options请求快速返回*/
  else  next();
});






/**
 * 拦截器配置
 */
const Authorization = require("../../../../ruoling-middleware/src/com/ruoling/middleware/Filter/Authorization.js");

app.use("/admin/*",Authorization)





//api封装
for(let i = 0;i<CommonApi.length;i++){
  app.use(CommonApi[i].key,CommonApi[i].value);
}




// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

 
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});


module.exports = app;
